Replace Int Without Variable
Rapid overview
Excellent interview-style question 💡
You can swap two integer values without using a third variable using either arithmetic operations or bitwise XOR.
Let’s go through both 👇
---
🧮 1️⃣ Method 1 — Using Arithmetic (Addition & Subtraction)
int a = 5;
int b = 10;
a = a + b; // a = 15
b = a - b; // b = 5
a = a - b; // a = 10
Console.WriteLine($"a = {a}, b = {b}");
✅ Output:
a = 10, b = 5
⚙️ How it works
- Step 1:
atemporarily holds the sum of both. - Step 2: Subtracting
bfrom sum gives originala. - Step 3: Subtracting new
bgives originalb.
⚠️ Caveat
- Risk of integer overflow if
a + bexceeds the data type’s range.
---
⚡ 2️⃣ Method 2 — Using Bitwise XOR
int a = 5;
int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
Console.WriteLine($"a = {a}, b = {b}");
✅ Output:
a = 10, b = 5
🧠 How it works
XOR has a neat property:
x ^ x = 0x ^ 0 = xx ^ y ^ y = x
So:
a = a ^ b→ combined info of a & bb = a ^ b→ becomes originalaa = a ^ b→ becomes originalb
✅ Pros
- No overflow risk
- Works perfectly for integers
---
🔍 3️⃣ Comparison
| Method | Uses | Overflow Risk | Works For | Readability |
|---|---|---|---|---|
| Arithmetic | +, - | ⚠️ Yes | Numeric types | Moderate |
| Bitwise XOR | ^ | ✅ No | Integers only | Less intuitive |
---
🚀 Interview Tip
If asked in an interview, say:
“There are two main ways — arithmetic or bitwise XOR. XOR is safer because it avoids overflow and doesn’t need extra storage.”
---
Would you like me to explain why the XOR trick mathematically guarantees that the two values swap back correctly (bitwise reasoning)?